package rmiClient;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.rmi.RemoteException;

import bl.service.TransmitFile;

public class DownloadFile {
		Client client = new Client();
		TransmitFile tf = client.getTransmitFile();

		public String download(String pathInServer , String pathInClient) {
			BufferedInputStream input = null;
			File save = new File(pathInClient);
			BufferedOutputStream output = null;

			File f = null;
			try {
				f = tf.downLoadFile(pathInServer);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (f == null)
				System.out.println("the file does not exist");
			else if (!save.exists()) {
				System.out.println("the file whose name is " + pathInServer
				 		+ " not existed ");
				try {
					save.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			//}
			// get content
		//	else {
				//System.out.println(f.length());
				//System.out.println((int)f.length());
				
				byte[] content = new byte[(int) f.length()];
				try {
					input = new BufferedInputStream(new FileInputStream(f));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {

					input.read(content);

					//System.out.println(content.length);
					output = new BufferedOutputStream(new FileOutputStream(save));
					output.write(content);
					input.close();
					output.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return pathInClient;
		}
	}
